package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.ChannelGroupJurisdiction;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.constant.HrPermissionConstants;
import org.jsola.hr.dao.IChannelGroupJurisdictionDAO;
import org.jsola.hr.dto.ChannelGroupJurisdictionAddDTO;
import org.jsola.hr.dto.ChannelGroupJurisdictionUpdateDTO;
import org.jsola.hr.entity.ChannelGroupJurisdictionDO;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.query.ChannelGroupJurisdictionQuery;
import org.jsola.hr.service.IChannelGroupJurisdictionService;
import org.jsola.hr.vo.ChannelGroupJurisdictionListVO;
import org.jsola.hr.vo.ChannelGroupJurisdictionVO;
import org.jsola.permission.constant.PermissionConstants;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.HrPermissionConstants.HR_DEFAULT_SUBJECT_ID;
import static org.jsola.hr.constant.HrPermissionConstants.SYSTEM_SUBJECT_TYPE;

/**
 * 渠道分组权限表
 *
 * @author zhr
 */
@Service("hrChannelGroupJurisdictionServiceImpl")
public class ChannelGroupJurisdictionServiceImpl implements IChannelGroupJurisdictionService {

    @Autowired
    private IChannelGroupJurisdictionDAO channelGroupJurisdictionDAO;

    @Autowired
    private IPermissionProviderService permissionProviderService;

    @Override
    public List<ChannelGroupJurisdictionDO> selectByUserId(String userId, TokenUser tokenUser) {
        Example example = new Example(ChannelGroupJurisdictionDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("userId", userId);
        List<ChannelGroupJurisdictionDO> channelGroupJurisdictionDOList = channelGroupJurisdictionDAO.selectByExample(example);
        if(CollectionUtils.isEmpty(channelGroupJurisdictionDOList)){
            return null;
        }
        return channelGroupJurisdictionDOList;
    }

    @Override
    public Integer getMyJurisdiction(TokenUser tokenUser) {
        String userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
        if (tokenUser.getUserId().equals(userId)) {
            return 0;
        } else {
            List<ChannelGroupJurisdictionDO> channelGroupJurisdictionDOList = selectByUserId(tokenUser.getUserId(), tokenUser);
            if(CollectionUtils.isEmpty(channelGroupJurisdictionDOList)){
                return -1;
            }else if(channelGroupJurisdictionDOList.size() == 1){
                return channelGroupJurisdictionDOList.get(0).getJurisdiction();
            }else if(channelGroupJurisdictionDOList.size() == 2){
                return 2;
            }
        }
        return -1;
    }

    @Override
    public List<ChannelGroupJurisdictionDO> getAllManagerByJurisdiction(int jurisdiction, TokenUser tokenUser) {
        Example example = new Example(ChannelGroupJurisdictionDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("jurisdiction", jurisdiction);
        return channelGroupJurisdictionDAO.selectByExample(example);
    }

    @Override
    public Integer batchSave(ChannelGroupJurisdictionAddDTO channelGroupJurisdictionAddDTO, TokenUser tokenUser) {
        //删除租户的特定权限
        ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery = new ChannelGroupJurisdictionQuery();
        channelGroupJurisdictionQuery.setJurisdiction(channelGroupJurisdictionAddDTO.getJurisdiction());
        List<ChannelGroupJurisdictionListVO> select = select(channelGroupJurisdictionQuery, tokenUser.getSiteId());
        if (!CollectionUtils.isEmpty(select)){
            String[] ids = select.stream().map(ChannelGroupJurisdictionListVO::getId).collect(Collectors.joining(",")).split(",");
            deleteByIds(tokenUser, ids);
        }
        //新增权限
        if(!CollectionUtils.isEmpty(channelGroupJurisdictionAddDTO.getUserIdList())){
            for (String userId : channelGroupJurisdictionAddDTO.getUserIdList()) {
                ChannelGroupJurisdictionAddDTO channelGroupJurisdictionAddDTO1 = new ChannelGroupJurisdictionAddDTO();
                channelGroupJurisdictionAddDTO1.setJurisdiction(channelGroupJurisdictionAddDTO.getJurisdiction());
                channelGroupJurisdictionAddDTO1.setUserId(userId);
                save(channelGroupJurisdictionAddDTO1,tokenUser);
            }
        }
        return 1;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public ChannelGroupJurisdictionVO save(ChannelGroupJurisdictionAddDTO channelGroupJurisdictionAddDTO, TokenUser tokenUser) {
//        //唯一校验
//        ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery = new ChannelGroupJurisdictionQuery();
//        channelGroupJurisdictionQuery.setUserId(channelGroupJurisdictionAddDTO.getUserId());
//        List<ChannelGroupJurisdictionListVO> select = select(channelGroupJurisdictionQuery, tokenUser.getSiteId());
//        if(!CollectionUtils.isEmpty(select)){
//            //更新权限
//            ChannelGroupJurisdictionUpdateDTO channelGroupJurisdictionUpdateDTO = new ChannelGroupJurisdictionUpdateDTO();
//            channelGroupJurisdictionUpdateDTO.setId(select.get(0).getId());
//            channelGroupJurisdictionUpdateDTO.setJurisdiction(channelGroupJurisdictionAddDTO.getJurisdiction());
//            channelGroupJurisdictionUpdateDTO.setUserId(channelGroupJurisdictionAddDTO.getUserId());
//            update(channelGroupJurisdictionUpdateDTO,tokenUser);
//            return channelGroupJurisdictionAddDTO.to(ChannelGroupJurisdictionVO.class);
//        }
        // 转DO
        ChannelGroupJurisdictionDO channelGroupJurisdictionDO = channelGroupJurisdictionAddDTO.to(ChannelGroupJurisdictionDO.class);
        // 保存
        channelGroupJurisdictionDO = save(channelGroupJurisdictionDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return channelGroupJurisdictionDO.to(ChannelGroupJurisdictionVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(ChannelGroupJurisdictionUpdateDTO channelGroupJurisdictionUpdateDTO, TokenUser tokenUser) {
        //转DO
        ChannelGroupJurisdictionDO channelGroupJurisdictionDO = channelGroupJurisdictionUpdateDTO.to(ChannelGroupJurisdictionDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(channelGroupJurisdictionDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... channelGroupJurisdictionIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) channelGroupJurisdictionIds);
    }


    @Override
    public ChannelGroupJurisdictionVO selectById(String channelGroupJurisdictionId, String siteId) {
        ChannelGroupJurisdictionDO channelGroupJurisdictionDO = selectDOById(channelGroupJurisdictionId, siteId);
        if (channelGroupJurisdictionDO == null) {
            return null;
        }
        return channelGroupJurisdictionDO.to(ChannelGroupJurisdictionVO.class);
    }

    @Override
    public List<ChannelGroupJurisdictionListVO> select(ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery, String siteId) {
        List<ChannelGroupJurisdictionDO> channelGroupJurisdictionDOList = selectDO(channelGroupJurisdictionQuery, siteId);
        if(CollectionUtils.isEmpty(channelGroupJurisdictionDOList)) {
            return channelGroupJurisdictionDOList == null ? null : new ArrayList<>();
        }
        return channelGroupJurisdictionDOList.stream()
                .map(channelGroupJurisdictionDO -> channelGroupJurisdictionDO.to(ChannelGroupJurisdictionListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery, String siteId) {
        Example example = buildExample(channelGroupJurisdictionQuery,siteId);
        return channelGroupJurisdictionDAO.selectCountByExample(example);
    }

    @Override
    public Page<ChannelGroupJurisdictionListVO> selectPage(ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery, String siteId) {
        Example example = buildExample(channelGroupJurisdictionQuery,siteId);
        Page<ChannelGroupJurisdictionDO> page = channelGroupJurisdictionDAO.selectPageByExample(example,
                channelGroupJurisdictionQuery.getPageNo(),
                channelGroupJurisdictionQuery.getPageSize());

        return page.to(ChannelGroupJurisdictionListVO.class);
    }

    @Override
    public ChannelGroupJurisdictionDO selectDOById(String channelGroupJurisdictionId, String siteId) {
        return listById(channelGroupJurisdictionId, siteId);
    }

    @Override
    public List<ChannelGroupJurisdictionDO> selectDO(ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery, String siteId) {
        Example example = buildExample(channelGroupJurisdictionQuery,siteId);
        return channelGroupJurisdictionDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param channelGroupJurisdictionQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery, String siteId) {
        Example example = new Example(ChannelGroupJurisdictionDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if(!StringUtils.isEmpty(channelGroupJurisdictionQuery.getUserId())){
            example.and().andEqualTo("userId",channelGroupJurisdictionQuery.getUserId());
        }
        if(channelGroupJurisdictionQuery.getJurisdiction() != null){
            example.and().andEqualTo("jurisdiction",channelGroupJurisdictionQuery.getJurisdiction());
        }
        // 排序
        ExampleKit.setExampleOrder(example,channelGroupJurisdictionQuery.getOrders());
        return example;
    }
}




